<template>
  <div class="createPost-container">
    <el-form v-loading="loading" ref="postForm" :model="postForm" :rules="rules" class="form-container">
      <div class="createPost-main-container">
        <el-card class="box-card" id="shopInfo">
          <div slot="header" class="clearfix">
            <span>产品基本信息</span>
          </div>
          <el-form-item style="margin-bottom: 40px;" prop="name">
            <MDinput v-model="postForm.name" :maxlength="100" name="name" required>
              产品名称
            </MDinput>
          </el-form-item>
          <div class="postInfo-container">
            <el-form-item label="产品分类:" prop="categoryId" class="postInfo-container-item">
              <Cascader v-model="categoryId" :ids="categoryIds" ref="categoryId" placeholder="产品分类"
                :options="categoryData" :props="props" class="filter-item" />
            </el-form-item>
            <el-form-item label="单位:" prop="unit" class="postInfo-container-item">
              <el-input v-model="postForm.unit" placeholder="单位" />
            </el-form-item>
          </div>
          <!-- <div class="postInfo-container">
            <el-form-item label="收货地:" prop="city" class="postInfo-container-item">
              <AddressCascader v-model="selectedOptions" @selectAddressDetail="selectAddressDetail" />
            </el-form-item>

          </div> -->
          <div class="postInfo-container">
            <el-form-item label="产品描述:" style="width:400px">
              <el-input v-model="postForm.productDetails" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" />
            </el-form-item>
            <el-form-item label="图片上传" prop="image">
              <UploadImage :image.sync="postForm.image" :limit="1" :type=1 />
               <!-- <Upload :default-image.sync="postForm.image" :validWidth="750" :validHeight="750" :size="1"/>
							<span style="color:#ff8704;">图片限制750*750px，大小在1M内</span> -->
            </el-form-item>
          </div>
        </el-card>
        <el-card class="box-card" id="matchInfo">
          <div slot="header" class="clearfix">
            <span>挂牌信息</span>
          </div>
          <div class="postInfo-container">
            <el-form-item label="期望价格（单价）:" prop="topPrice" class="postInfo-container-item">
              <NumInput :min="1" :float="2" v-model="postForm.topPrice" />
            </el-form-item>
            <el-form-item label="期望数量:" prop="topNum" class="postInfo-container-item">
              <NumInput :min="1" :float="2" v-model="postForm.topNum" />
            </el-form-item>
          </div>
          <div class="postInfo-container">
            <el-form-item label="其他要求:" style="width:400px">
              <el-input v-model="postForm.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" />
            </el-form-item>
          </div>
          <div class="postInfo-container">
            <el-form-item label="付款说明:" style="width:400px">
              <el-input v-model="postForm.payRemark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" />
            </el-form-item>
          </div>
          <el-form-item label="挂牌时间:" prop="startDate" style="width:400px">
            <DatePicker :startDate.sync="postForm.startDate" :endDate.sync="postForm.endDate" clearable />
          </el-form-item>
        </el-card>
        <el-form-item style="margin-bottom: 30px;">
          <el-button type="primary" @click="submitForm">
            发布
          </el-button>
        </el-form-item>
      </div>
    </el-form>
    <div class="toInfo">
      <a @click.prevent="anchor('shopInfo')">产品信息</a>
      <a @click.prevent="anchor('matchInfo')">挂牌信息</a>
    </div>
  </div>
</template>
<script>
import MDinput from '@/components/MDinput'
import UploadImage from '@/components/UploadImage'
import NumInput from '@/components/NumInput'
import Cascader from '@/components/Cascader'
import DatePicker from '@/components/DatePicker'
import AddressCascader from '@/components/AddressCascader'
import { categoryPageVoByQo } from '@/api/product'
import { matchSave, matchGetById } from '@/api/transaction'
import Upload from '@/components/Upload'

const defaultForm = {
  name: '',
  categoryId: '',
  unit: '吨',
  startProvinceId: '',
  startProvinceName: '',
  startCityId: '',
  startCityName: '',
  startDistrictId: '',
  startDistrictName: '',
  remark: '',
  topNum: '',
  topPrice: '',
  subPrice: '',
  startDate: '',
  endDate: '',
  payRemark: '',
  productDetails:'',
  image:''
}

export default {
  name: 'matchBuyingSave',
  components: { MDinput, Cascader, AddressCascader, NumInput, DatePicker,Upload, UploadImage },
  data() {
    const validateDate = (rule, value, callback) => {
      if (!this.postForm.startDate || !this.postForm.endDate) {
        callback(new Error('请选择时间'))
      } else if (new Date(this.postForm.startDate).getTime() < new Date().getTime()) {
        callback(new Error('起始时间必须晚于当前时间'))
      } else if(this.postForm.startDate == this.postForm.endDate) {
				callback(new Error('起始时间不能等于当前时间'))
			} else {
        callback()
      }
    }

    const validateCity = (rule, value, callback) => {
      if (!this.postForm.startDistrictId) {
        callback(new Error('请选择省市区'))
      } else {
        callback()
      }
    }
    return {
      postForm: Object.assign({}, defaultForm),
      categoryData: [],
      categoryId: '',
      categoryIds: '',
      props: { value: 'id', label: 'name' },
      selectedOptions: [],
      loading: false,
      userListOptions: [],
      rules: {
        categoryId: [{ required: true, message: '请选择', trigger: 'blur' }],
        unit: [{ required: true, message: '请输入', trigger: 'blur' }],
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        // remark: [{ required: true, message: '请输入图文详情', trigger: 'blur' }],
        city: [{ required: true, trigger: 'blur', validator: validateCity }],
        topPrice: [{ required: true, message: '请输入', trigger: 'blur' }],
        topNum: [{ required: true, message: '请输入', trigger: 'blur' }],
        subPrice: [{ required: true, message: '请输入', trigger: 'blur' }],
        startDate: [{ validator: validateDate }],
      },
      productId: 0,
    }
  },
  watch: {
    categoryId(val) {
      this.$set(this.postForm, `categoryId`, this.$refs['categoryId'].getIds(val))
    }
  },
  created() {
    this.productId = this.$route.query && Number(this.$route.query.id);
    this.getCategory();
  },
  methods: {
    /*锚链接跳转*/
    anchor(anchorName) {
      /*找到锚点*/
      let anchorElement = document.getElementById(anchorName);
      /*如果对应id的锚点存在，就跳转到锚点*/
      if (anchorElement) {
        //behavior定义动画过渡效果， "auto"或 "smooth" 之一。默认为 "auto"
        anchorElement.scrollIntoView({ behavior: "smooth" });
      }
    },
    init(val) {
      this.$nextTick(() => {
        if (val.startDistrictId) {
          this.selectedOptions = [val.startProvinceId.toString(), val.startCityId.toString(), val.startDistrictId.toString()]
        } else {
          this.selectedOptions = ''
        }

        this.categoryIds = val.categoryId ? val.categoryId.toString() : '';
      })
    },
    selectAddressDetail(value) {
      if (value) {
        this.$set(this.postForm, `startProvinceId`, value.provinceId)
        this.$set(this.postForm, `startProvinceName`, value.provinceName)
        this.$set(this.postForm, `startCityId`, value.cityId)
        this.$set(this.postForm, `startCityName`, value.cityName)
        this.$set(this.postForm, `startDistrictId`, value.districtId)
        this.$set(this.postForm, `startDistrictName`, value.districtName)
      } else {
        this.$set(this.postForm, `startProvinceId`, '')
        this.$set(this.postForm, `startProvinceName`, '')
        this.$set(this.postForm, `startCityId`, '')
        this.$set(this.postForm, `startCityName`, '')
        this.$set(this.postForm, `startDistrictId`, '')
        this.$set(this.postForm, `startDistrictName`, '')
      }
    },
    getCategory() {
      categoryPageVoByQo().then((res) => {
        // let array = [];
        // res.forEach(function(item, index) {
        // 	let data = {};
        // 	data.name = item.name;
        // 	data.id = item.id;
        //   array.push(data);
        // });
        // this.$set(this, 'categoryData', array || [])

        this.$set(this, 'categoryData', res || [])
        if (this.productId) {
          this.fetchData(this.productId);
        }
      })
    },
    fetchData(id) {
      matchGetById(id).then(res => {
        this.postForm = Object.assign({}, res);
        this.$delete(this.postForm, "createTime");
        this.init(res);
      }).catch(err => {

      })
    },
    submitForm() {
      this.$refs['postForm'].validate((valid) => {
        if (valid) {
          this.loading = true
          let isEdit = this.productId > 0;

          let isSave = this.$route.query && this.$route.query.isSave;
          if (isSave) {
            isEdit = false
            this.$delete(this.postForm, "id");
          }

          matchSave(this.postForm, isEdit).then(() => {
            this.loading = false

            this.$message({
              message: '发布成功',
              type: 'success'
            });
            this.$router.push('/transaction/match')
          }).catch(() => {
            this.loading = false
          })
        }
      })
    },
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
        margin-right: 20px;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}
.toInfo {
  position: fixed;
  right: 5px;
  bottom: 40vh;
  // border: 1px solid #eee;
  border-radius: 2px;
  box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.2);
  background: rgba(255, 255, 255, 0.5);
  a {
    display: block;
    padding: 10px;
    border-bottom: 1px solid #eee;
    &:last-child {
      border: none;
    }
  }
}
.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
.box-card {
  margin-bottom: 30px;
  .flexItem {
    display: flex;
    align-items: center;
    .fuhao {
      margin-right: 3px;
      font-size: 16px;
      color: red;
    }
    .el-input {
      width: auto;
      flex: 1;
    }
  }
}
</style>
